package com.starlink.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.convert.Convert;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import com.starlink.client.ras.RasClient;
import com.starlink.client.ras.request.GoodsListEvidenceRequest;
import com.starlink.client.ras.response.GoodsListEvidenceResponse;
import com.starlink.client.ras.response.RasBaseResponse;
import com.starlink.common.PageQueryRequest;
import com.starlink.common.enums.ErrorCode;
import com.starlink.common.exception.BusinessException;
import com.starlink.model.domain.MallIntegrationOrderDO;
import com.starlink.model.vo.mall.AdminIntegratonArticlesVO;
import com.starlink.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import com.starlink.common.utils.AssertUtil;
import com.starlink.model.dtomapper.MallIntegrationDtoMapper;
import com.starlink.model.domain.MallIntegrationDO;
import com.starlink.mapper.MallIntegrationMapper;
import com.starlink.model.request.MallIntegrationRequest;
import com.starlink.model.util.MallIntegrationConvert;
import com.starlink.model.vo.MallIntegrationVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static com.starlink.common.enums.OrderTypeEnum.BOOK;
import static com.starlink.common.enums.OrderTypeEnum.RIM;
import static com.starlink.common.enums.PaymentTypeEnum.JI_FEN_MONEY_PAY;
import static com.starlink.utils.IDUtils.getId;
import static com.starlink.utils.PageUtils.getOrderBy;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author zhanghong
 */
@Service
public class MallIntegrationServiceImpl extends ServiceImpl<MallIntegrationMapper, MallIntegrationDO> implements MallIntegrationService {
    @Autowired
    private MallIntegrationMapper mallIntegrationMapper;
    @Autowired
    private MallBooksService mallBooksService;
    @Autowired
    private MallBooksSpecificationService booksSpecificationService;
    @Autowired
    private MallIntegrationOrderService integrationOrderService;
    @Autowired
    private MallPeripherySpecificationService peripherySpecificationService;
    @Autowired
    private RasClient rasClient;

    @Override
    public MallIntegrationVO getByKey(long id) {
        MallIntegrationVO mallIntegrationVO = mallIntegrationMapper.selectByIdOverrride(id);
        return mallIntegrationVO;
    }

    @Override
    public PageInfo<MallIntegrationVO> pageQuery(Pageable pageable,MallIntegrationRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), getOrderBy(pageable.getSort())).setReasonable(true);
        List<MallIntegrationVO> list = mallIntegrationMapper.pageQuery(request);
        return new PageInfo(list);
    }

    @Override
    public List<MallIntegrationVO> listQuery(MallIntegrationRequest request) {
        List<MallIntegrationDO> list = mallIntegrationMapper.selectDOList(MallIntegrationDtoMapper.INSTANCE.request2DO(request));
        List<MallIntegrationVO> mallIntegrationVOS = MallIntegrationConvert.buildMallIntegrationVoList(list);
        return mallIntegrationVOS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean add(MallIntegrationRequest request) {
        Long articlesId = request.getArticlesId();
        Long freeTemplateId = request.getFreeTemplateId();
        Integer articlesCategory = request.getArticlesCategory();
        Long integralPrice = request.getIntegralPrice();
        Long exchangeInventory = request.getExchangeInventory();
        Integer paymentType = request.getPaymentType();
        BigDecimal price = request.getPrice();
        String title = request.getTitle();
        String picture = request.getPicture();
        Long specificationId = request.getSpecificationId();
        AssertUtil.assertNotNull(articlesId,"关联商品ID不能为空!");
        AssertUtil.assertNotNull(freeTemplateId,"运费模板ID不能为空!");
        AssertUtil.assertNotNull(articlesCategory,"商品类别不能为空!");
        AssertUtil.assertNotNull(integralPrice,"积分不能为空!");
        AssertUtil.assertNotNull(exchangeInventory,"兑换库存不能为空!");
        AssertUtil.assertNotNull(paymentType,"支付类型不能为空!");
        AssertUtil.assertNotNull(title,"商品名称不能为空!");
        AssertUtil.assertNotNull(picture,"商品图片不能为空!");
        AssertUtil.assertNotNull(specificationId,"商品规格ID不能为空!");
        if (exchangeInventory<0){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "兑换库存不能小于0!");
        }
        if (JI_FEN_MONEY_PAY.getType().equals(paymentType)){
            AssertUtil.assertNotNull(price,"金额不能为空!");
        }
        request.setOnTheShelf(0);
        request.setCreateTime(new Date());
        request.setSurplusInventory(exchangeInventory);
        request.setId(getId());
        save(MallIntegrationDtoMapper.INSTANCE.request2DO(request));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByKey(MallIntegrationRequest request) {
        AssertUtil.assertNotNull(request.getId(), "id不能为空!");
        if (BOOK.equals(request.getArticlesCategory()) && request.getOnTheShelf()!=null) {
            Long rasGoodsId = request.getRasGoodsId();
            AssertUtil.assertNotNull(rasGoodsId, "RAS商品ID不能为空!");
            GoodsListEvidenceRequest evidenceRequest = new GoodsListEvidenceRequest();
            evidenceRequest.setId(rasGoodsId.intValue());
            RasBaseResponse<GoodsListEvidenceResponse> goodsListEvidence = rasClient.goodsListEvidence(evidenceRequest);
            GoodsListEvidenceResponse listEvidenceData = goodsListEvidence.getData();
            GoodsListEvidenceResponse.RasGoodsListPageDTO rasGoodsListPage = listEvidenceData.getRasGoodsListPage();
            List<GoodsListEvidenceResponse.RasGoodsListPageDTO.RecordsDTO> records = rasGoodsListPage.getRecords();
            AssertUtil.assertNotEmpty(records, "该积分商品关联的书籍RAS审核还未通过,暂不能上架!");
        }
        saveOrUpdate(MallIntegrationDtoMapper.INSTANCE.request2DO(request));
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteDOByIds(String ids) {
        if (StringUtils.isEmpty(ids)){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "ID不能为空!");
        }
        Long id = Long.valueOf(ids);
        List<MallIntegrationOrderDO> integrationOrderDOS = integrationOrderService.lambdaQuery().eq(MallIntegrationOrderDO::getMallIntegrationId, id).list();
        List<MallIntegrationDO> integrationDOs = this.lambdaQuery().eq(MallIntegrationDO::getId, id).list();
        if (CollectionUtils.isNotEmpty(integrationOrderDOS)){
            throw new BusinessException("该商品存在订单,暂不能删除");
        }
        List<Map<String, Long>> maps = new ArrayList<>();
        integrationDOs.forEach(integrationDO->{
            Long specificationId = integrationDO.getSpecificationId();
            Integer articlesCategory = integrationDO.getArticlesCategory();
            Long surplusInventory = integrationDO.getSurplusInventory();
            Integer onTheShelf = integrationDO.getOnTheShelf();
            if (onTheShelf==1){
                throw new BusinessException(ErrorCode.PARAM_ERROR, "商品处于上架状态不能删除!");
            }
            Map<String, Long> map = new HashMap<>();
            map.put("specificationId",specificationId);
            map.put("quantity",surplusInventory);
            map.put("articlesCategory",articlesCategory.longValue());
            maps.add(map);
        });
        //归还库存
        maps.forEach(map->{
            if (BOOK.getType().equals(map.get("articlesCategory").intValue())){
                booksSpecificationService.addQuantity(map);
            }else if (RIM.getType().equals(map.get("articlesCategory").intValue())){
                peripherySpecificationService.addQuantity(map);
            }
        });

        mallIntegrationMapper.deleteDOByIds(Convert.toStrArray(ids));
        return true;
    }

    @Override
    public PageInfo<List<MallIntegrationVO>> pageList(Pageable pageable, MallIntegrationRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), getOrderBy(pageable.getSort())).setReasonable(true);
        List<MallIntegrationVO> list = mallIntegrationMapper.pageList(request);
        return new PageInfo(list);
    }

    @Override
    public PageInfo<AdminIntegratonArticlesVO> pageQueryArticles(Pageable pageable, PageQueryRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize(), getOrderBy(pageable.getSort())).setReasonable(true);
        List<AdminIntegratonArticlesVO> list = mallIntegrationMapper.pageQueryArticles();
        return new PageInfo(list);
    }
}